<template>
  <!-- 操作日志页面 -->
  <el-card>
    <!-- 搜索条件 -->
    <div class="searchForm">
      <el-form :model="searchForm">
        <!-- 第一行 -->
        <span>操作人员：</span>
        <el-input v-model="searchForm.createName" />
        <el-config-provider :locale="locale">
          <span>操作日期：</span>
          <el-date-picker v-model="searchForm.timeRange" type="datetimerange" format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期"
            :default-time="defaultTime" range-separator="至" />
        </el-config-provider>
        <br />
        <!-- 第二行 -->
        <div class="right">
          <el-button class="search" type="primary" icon="Search" size="small" @click="subSearch">搜索</el-button>
          <el-button class="reset" type="info" icon="RefreshRight" size="small" @click="subReset">重置</el-button>
        </div>
        <br />
        <br>
        <hr style="background-color: #5aa2cc; height: 0.5px; border: none" />
      </el-form>
    </div>
    <!-- 操作表格按钮 -->
    <div class="operateButton">
      <el-button type="primary" class="tableDelete" @click="handleDelete" icon="Delete" size="small">删除</el-button>
      <el-button type="primary" class="tableEmpty" @click="handleEmpty" icon="DeleteFilled" size="small">清空</el-button>
      <el-button type="primary" class="tableExport" @click="handleExport" icon="Download" size="small">导出</el-button>
    </div>
    <br />
    <!-- 操作日志表格 -->
    <div class="common-table">
      <el-table :data="tableLogData" stripe @selection-change="handleSelectionChange" style="width: 100%" v-if="tableLogData.length > 0">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="日志编号" :key="index" />
        <el-table-column prop="createName" label="访问人" :key="index" />
        <el-table-column prop="content" label="操作类型" :key="index" />
        <el-table-column prop="ip" label="主机" :key="index" />
        <!-- <el-table-column prop="state" label="操作状态" :key="index" /> -->
        <el-table-column prop="createTime" label="操作日期" :key="index" />
        <el-table-column fixed="right" label="操作">
          <template #default="{ row }">
            <el-button link type="primary" size="small" icon="View" @click="submitDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else style="margin-top: 54px;">
        <el-empty description="暂无数据" />
      </div>

      <div class="pager">
        <!-- 分页 -->
        <el-pagination v-show="total > 0" v-model:page="searchForm.pageNum" v-model:limit="searchForm.pageSize"
          layout="prev, pager, next" :total="total" @update:current-page="handlePage" />
      </div>

      <!-- 抽屉 -->
      <!-- <el-drawer v-model="drawerVisible" :direction="direction" :before-close="drawerClose" :title="drawerTitle">
      <div class="drawer-main">
        <p><span class="tit">标题</span><i>：</i><span class="con">{{ newsDrawerForm.title }}</span></p>
        <p><span class="tit">发布人</span><i>：</i><span class="con">{{ newsDrawerForm.createName }}</span></p>
        <p><span class="tit">发布时间</span><i>：</i><span class="con">{{ newsDrawerForm.createTime }}</span></p>
        <p><span class="tit">发布状态</span><i>：</i><span class="con">{{ newsDrawerForm.status == 1 ? '已发布' :
          '未发布' }}</span></p>
        <p><span class="tit">上传图片</span><i>：</i><a @click="PreviewDrawerPDF">{{ newsDrawerForm.fileList }}</a>
        </p>
      </div>
    </el-drawer> -->

      <!-- 弹窗 -->
      <el-dialog v-model="dailyVisible" :title="dailyTitle" width="50%" :before-close="dailyClose"
        :close-on-click-modal="false">
        <div v-loading="btnDisabled" element-loading-text="图片上传中...">
          <el-form ref="ruleFormRef" :model="newsForm" status-icon :rules="rules" label-width="110px">
            <el-form-item label="标题" prop="title" style="margin-left:13px;">
              <el-input v-model="newsForm.title" type="textarea" resize="none" :rows="2" autocomplete="off"
                placeholder="请输入标题" maxlength="20" :show-word-limit="false" />
            </el-form-item>

            <!-- 上传图片 -->
            <el-form-item label="上传图片" prop="file" style="margin-left:13px;">
              <el-upload v-model:file-list="newsForm.fileList" action="#" list-type="picture-card" :limit="1"
                :http-request="uploadAction" :before-upload="beforeUpload" accept="image/*" :on-remove="handleRemove"
                :on-exceed="handleExceedCover">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item style="margin-left:13px;">
              <el-button @click="resetForm()">取消</el-button>
              <el-button type="primary" @click="confirmAdd()">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script setup>
import locale from "element-plus/lib/locale/lang/zh-cn"; // 中文语言
import { ref, reactive } from 'vue'

import { getLogIdList, getLogList, addLog, updateLog, delLogs } from '../../api/log/index'

const defaultTime = new Date(2000, 1, 1, 12, 0, 0);
const total = ref()   //表示数据的总条数

const btnDisabled = ref(false); //按钮禁止


//操作日志表格数据
const tableLogData = ref([])
// {
//   id: "1111",
//   createName: "赵健",
//   operateType: "登录",
//   ip: "49.77.183.52",
//   state: "成功",
//   operateTime: "2023-03-30 12:33:33",
// },
// {
//   id: "1222",
//   createName: "明燊",
//   operateType: "登录",
//   ip: "49.77.183.52",
//   state: "失败",
//   operateTime: "2023-03-30 12:33:33",
// },
// {
//   id: "2222",
//   createName: "赵健",
//   operateType: "登出",
//   ip: "49.77.183.52",
//   state: "成功",
//   operateTime: "2023-03-30 12:33:33",
// },



// const logForm = ref({
//   id: undefined,
//   title: undefined,//标题
//   file: [],//封面url
//   createName: JSON.parse(localStorage.getItem("userInfo")).fullName,

//   orgId: JSON.parse(localStorage.getItem("userInfo")).orgId,//单位id
//   status: 0, //是否发布
//   updateTime: undefined,
//   fileList: [],//文件暂存
// })
// //重置
// function logFormRest() {
//   logForm.value.id = undefined;
//   logForm.value.title = undefined;
//   logForm.value.file = [];
//   logForm.value.createName = JSON.parse(localStorage.getItem("userInfo")).fullName,
//   logForm.value.orgId = JSON.parse(localStorage.getItem("userInfo")).orgId;
//   logForm.value.status = 0;
//   logForm.value.updateTime = undefined;
//   logForm.value.fileList = [];
// }
// //图片校验
// const validateFileId = (rule, value, callback) => {
//   if (value == "") {
//     callback(new Error('请上传图片'))
//   } else {
//     callback()
//   }
// }

// const rules = reactive({
//   title: [{ required: true, message: '标题不能为空', trigger: 'blur', }, { max: 20, message: '字数超出20字', trigger: 'blur' }],
//   file: [{ required: true, validator: validateFileId, trigger: "blur" }],
// })


const ruleFormRef = ref('');
//编辑(新增)弹窗
const dailyVisible = ref(false)
//抽屉(详情)弹窗
const drawerVisible = ref(false)
const direction = ref('rtl')
//抽屉弹窗
const drawerTitle = ref("")
const logDrawerForm = ref({
  id: undefined,
  title: undefined,//标题
  file: [],//封面url
  createName: JSON.parse(localStorage.getItem("userInfo")).fullName,
  orgId: JSON.parse(localStorage.getItem("userInfo")).orgId,//单位id
  status: 0, //是否发布
  updateTime: undefined,
  fileList: [],//文件暂存
})
//重置
function logDrawerFormRest() {
  logForm.value.id = undefined;
  logForm.value.title = undefined;
  logForm.value.file = [];
  logForm.value.createName = JSON.parse(localStorage.getItem("userInfo")).fullName,
    logForm.value.orgId = JSON.parse(localStorage.getItem("userInfo")).orgId;
  logForm.value.status = 0;
  logForm.value.updateTime = undefined;
  logForm.value.fileList = [];
}
//关闭抽屉
const drawerClose = () => {
  logDrawerFormRest()
  drawerVisible.value = false
}

// 状态选择
const optionState = [
  {
    value1: 1,
    label: "已发布",
  },
  {
    value1: 0,
    label: "未发布",
  },
];
//操作栏数据
const searchForm = reactive({
  // title: undefined,
  // status: undefined,
  timeRange: [],
  createName: '',
  pageNum: 1,//页码
  pageSize: 12,//条数
  sectionDate: [],
  // updateBeginTime: undefined,
  // updateEndTime: undefined
});


//操作栏重置
const subReset = () => {
  searchForm.title = undefined
  searchForm.createName = undefined
  searchForm.timeRange = []
  searchForm.status = undefined
  searchForm.pageNum = 1
  searchForm.pageSize = 12
  getList()
  // searchForm.sectionDate = []
  // searchForm.updateBeginTime = undefined
  // searchForm.updateEndTime = undefined
}

//搜索列表的查询
const subSearch = () => {
  getList()
}

const isEdit = ref(false) //是否为编辑
const dailyTitle = ref() //是否为编辑

//新增
const handleNews = () => {
  dailyTitle.value = "新增新闻"
  isEdit.value = false
  dailyVisible.value = true
  // if (JSON.parse(sessionStorage.getItem("zhgd_userList")).orgType != "1") {
  //   approver.value = true
  //   getRoleLeader().then(res => {
  //     approverList.value = res.data
  //     dailyRuleForm.value.approvalUserId = res.data[0].userId
  //   })
  // }
}
const dailyClose = () => {
  logFormRest()
  isEdit.value = false
  dailyVisible.value = false
}
// //重置表单
const resetForm = () => {
  logFormRest()
  isEdit.value = false
  dailyVisible.value = false;
}
//编辑
const submitDetail = (row) => {
  ElMessage({
    message: '暂未接入',
    type: 'success',
  })
  // dailyTitle.value = "编辑新闻"
  // isEdit.value = true
  // dailyVisible.value = true
  // // logForm.value = row
  // // logForm.value.fileList = logForm.value.fileUrl.map(item=>{
  // //   return item.localAddress
  // // })

  // getLogIdList(row.id).then(({ data }) => {
  //   console.log(data, 'data');
  //   if (data.code == 200) {
  //     logForm.value = data.data
  //     logForm.value.fileList = logForm.value.fileUrl.map(item => {
  //       let obj ={}
  //       obj.url = `${item.prefix}` + `${item.fileName}`
  //       return obj
  //       // obj.url = obj.url.replace(undefined, '')
  //     })
  //       console.log(logForm.value,'logForm.value');
  //   }
  // });
}


const tableLoading = ref(false)
//获取新闻进行刷新列表
function getList() {
  // tableData = []
  tableLogData.value = []
  tableLoading.value = true;
  getLogList(searchForm).then(({ data }) => {
    if (data.code == 200) {
      tableLoading.value = false;
      // tableData = data.data.list
      tableLogData.value = data.data.list

      total.value = data.data.totalCount




      //图片地址
      // tableList.value.forEach(item => {
      //   if (item.file) {
      //     item.file =  item.file
      //   }
      // })
    }
  })
}

// 点击发布
const submitCancel = (row) => {
  getNewsRelease(row.id, 1).then(({ data }) => {
    if (data.code != 200) {
      ElMessage({
        message: '发布失败',
        type: 'error',
      })
    } else {
      ElMessage({
        message: '发布成功',
        type: 'success',
      })
      getList()
    }
  })
}

// 点击取消发布
const submitCancelIssue = (row) => {
  getNewsRelease(row.id, 0).then(({ data }) => {
    if (data.code != 200) {
      ElMessage({
        message: '取消失败',
        type: 'error',
      })
    } else {
      ElMessage({
        message: '取消成功',
        type: 'success',
      })
      getList()
    }
  })
}

// 点击详情
const submitDetail2 = (row) => {

  // row.file.forEach(item => {
  //   fileList.push(item.url)
  // });
  drawerVisible.value = true
  drawerTitle.value = "新闻详情"
  logDrawerForm.value = row
  // let data = {
  //   id: val.id,
  // }


}

// 点击删除
const submitDel = (row) => {
  ElMessageBox.confirm("你确定删除吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delLogs({ id: row.id }).then(res => {
        if (res.data.code != 200) {
          ElMessage({
            message: '删除失败',
            type: 'error',
          })
          getList()
        } else {
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
          getList()
        }
      })

    })
    .catch(() => {
    });
}
//图片接口
const uploadAction = (val) => {
  btnDisabled.value = true;
  let param = new FormData();
  param.append("file", val.file);
  uploadImage(param).then(({ data }) => {
    if (data.code == 200) {
      console.log(data, 'res');
      btnDisabled.value = false // 上传成功之后关闭上传中状态并提示上isLt1M传成功
      // props.dataForm.form.taskInfo.imageUrl.push(data.data[0])
      logForm.value.file.push(data.data[0])
      if (!data.data[0].url) return
    }
  });
};
const beforeUpload = (file) => {
  //大小小于5M
  const isLt1M = file.size / 1024 / 1024 < 10;
  if (!isLt1M) {
    ElMessage({
      message: "上传图片大小不能超过10MB！",
      type: "warning",
    });
    return false;
  }
  const fileSuffix = file.name
    .substring(file.name.lastIndexOf(".") + 1)
    .toLowerCase();
  // console.log(fileSuffix,'fileSuffix')
  const whiteList = ["png", "jpg", "jpeg"];
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage({
      message: "上传文件只能是图片格式！",
      type: "warning",
    });
    return false;
  }
  return true;
};

//超过限制的回调
const handleExceedCover = (files, fileList) => {
  ElMessage.error({
    message: `上传图片数量超出限制！`,
    type: 'error',
  })
}
const handleRemove = (file) => {

  logForm.value.file = logForm.value.file.filter(item => {
    return item.name != file.name
  })

  return true;
};

//确定新增/编辑
// const confirmAdd = () => {
//   ruleFormRef.value.validate((valid) => {
//     if (valid) {
//       //编辑
//       if (isEdit.value) {
//         updateLog(logForm.value).then(res => {
//           dailyVisible.value = false
//           logFormRest()
//           ElMessage.closeAll();
//           if (res.code == 200) {
//             ElMessage({
//               message: '编辑成功',
//               type: 'success',
//             })
//           }
//           getList();
//         })
//       } else {
//         addLog(logForm.value).then(res => {
//           dailyVisible.value = false
//           logFormRest()
//           ElMessage.closeAll();
//           if (res.data.code == 200) {
//             ElMessage({
//               message: '新增成功',
//               type: 'success',
//             })
//             getList();
//           } else {

//           }

//         })
//       }
//     } else {
//       console.log('error submit!')
//       return false
//     }
//   })
// }




// 点击删除
const handleDelete = () => {
  ElMessage({
    message: '暂未接入',
    type: 'success',
  })
}

// 点击清空
const handleEmpty = () => {
  ElMessage({
    message: '暂未接入',
    type: 'success',
  })
}

// 点击导出
const handleExport = () => {
  console.log("点击导出");
}



//分页
const handlePage = (val) => {
  searchForm.pageNum = val //更新页码
  getList()
}

onMounted(() => {
  getList()

})

</script>

<style lang="less" scoped>
.searchForm {

  .el-input,
  .el-select {
    width: 130px;
  }

  span {
    font-size: 14px;
    margin-left: 20px;
  }

  .el-button:hover {
    opacity: 0.7;
  }

  .right {
    float: right;
    padding-right: 20px;

    .search {
      margin: 5px;
    }
  }
}

.operateButton {
  .tableDelete {
    background-color: #f1b6b6;
    border: none;
  }

  .tableEmpty {
    background-color: #c2a3a3;
    border: none;
  }

  .tableExport {
    background-color: #c4c599;
    border: none;
  }
}


.el-table {
  font-size: 12px;
  --el-table-header-bg-color: #dadada9d;
}

:deep(.el-table .cell) {
  text-align: center;
}

.el-link {
  font-size: 12px;
  font-family: Arial;
  padding-right: 15px;
}

.main-top {
  height: 20vh;
}



.drawer-main {
  width: 100%;
  padding: 0 16px;

  p {
    display: flex;
    font-size: 16px;
    color: #333;
    line-height: 24px;
    margin-bottom: 20px;
    word-break: break-all;
    word-wrap: break-word;

    S span {
      display: inline-block;
    }

    .tit {
      width: 95px;
      text-align: justify;
      text-align-last: justify;
    }

    i {
      display: inline-block;
      width: 30px;
      font-style: normal;
      font-weight: normal;
    }

    a {
      flex: 1;
      font-style: normal;
      font-weight: normal;
      cursor: pointer;
      color: #4286ff;
    }

    .con {
      flex: 1;
    }
  }
}

.table-tips {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis; //超出范围用'...'代替
  white-space: nowrap;
}

.pager {
  display: flex;
  flex-direction: row-reverse;
  // position: absolute;
  // right: 100px;
  // bottom: 50px;

  .pagination-container {
    position: relative;
  }
}
</style>